package com.sls.mall.product.exception;

import com.sls.mall.common.exception.SLSCodeEnume;
import com.sls.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lixue
 * @Title: SlsExceptionController
 * @ProjectName sls_mall2021
 * @Description: TODO
 * @date 2021/4/2811:40
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.sls.mall.product.controller")
public class SlsExceptionController {


    // 精确异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e)
    {
        log.error("");

        Map<String,Object> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().stream().forEach((item) -> {
            String field = item.getField();
            String message = item.getDefaultMessage();

            map.put(field,message);
        });
        return R.error(SLSCodeEnume.VAILD_EXCEPTION.getCode(),SLSCodeEnume.VAILD_EXCEPTION.getMessage()).put("data",map);
    }

    // 兜底的异常返回方法
    @ExceptionHandler(value = Throwable.class)
    public R handelException(Throwable e)
    {
        return R.error(SLSCodeEnume.UNKNOW_EXCEPTION.getCode(),SLSCodeEnume.UNKNOW_EXCEPTION.getMessage());
    }
}
